using System.Collections.Generic;
using System.Linq;
using Engine.Core.Interfaces;
using Engine.Particles.Interfaces;
using Microsoft.Xna.Framework;

namespace Engine.Particles
{
    public class ParticleEngine : IParticleEngine {
        public List<IParticleEffect> ParticleEffects { get; set; }


        public void AddParticleEffect(IParticleEffect particleEffect) {
            if (EffectsCount <= MaxAmountOfEffects)
                ParticleEffects.Add(particleEffect);
        }

        public ParticleEngine() {
            ParticleEffects = new List<IParticleEffect>();
            MaxAmountOfEffects = 50;
        }

        public virtual void Update(GameTime gameTime) {
            foreach (var particleEffect in ParticleEffects) {
                particleEffect.Update(gameTime);
            }
            Cleanup();
            ParticleEffects.ForEach(x => x.Update(gameTime));
        }

        private void Cleanup() {
            var effects = new List<IParticleEffect>();
            foreach (var particleEffect in ParticleEffects) {
                if (particleEffect.HasEnded)
                    effects.Add(particleEffect);
            }
            effects.ForEach(x => ParticleEffects.Remove(x));
        }

        public List<IExtendedDrawable> GetDrawables() {
            return ParticleEffects.SelectMany(x => x.GetDrawables()).ToList();
        }

        public List<IPhysicElement>  GetPhysicElements() {
            return ParticleEffects.SelectMany(x => x.GetPhysicObjects()).ToList();
        }

        public int MaxAmountOfEffects { get; set; }

        public int EffectsCount {
            get { return ParticleEffects.Count; }
        }
    }
}